package com.zhang.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zhang.common.util.result.R;
import com.zhang.common.util.result.RUtils;
import com.zhang.goods.entity.AttrAttrgroup;
import com.zhang.goods.entity.Attrgroup;
import com.zhang.goods.entity.Attribute;
import com.zhang.goods.entity.Category;
import com.zhang.goods.mapper.AttributeMapper;
import com.zhang.goods.service.IAttrAttrgroupService;
import com.zhang.goods.service.IAttrgroupService;
import com.zhang.goods.service.IAttributeService;
import com.zhang.goods.service.ICategoryService;
import com.zhang.goods.vo.AttrVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品属性表 服务实现类
 * </p>
 *
 * @author 创世神
 * @since 2023-09-12
 */
@Slf4j
@Service
public class AttributeServiceImpl extends ServiceImpl<AttributeMapper, Attribute> implements IAttributeService {
    @Autowired
    private IAttrAttrgroupService assoAttrAttrGroup;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IAttrgroupService groupService;

    @Override
    @Transactional
    public R addAttr(Attribute attribute) {
        save(attribute);
        if (attribute.getAttrGroupId() != null && attribute.getAttrType() == 1) {
            /*关联操作*/
            AttrAttrgroup asso = new AttrAttrgroup();
            asso.setAttrId(attribute.getId());
            asso.setAttrGroupId(attribute.getAttrGroupId());
            assoAttrAttrGroup.save(asso);
        }
        return RUtils.successMsg("新增成功");
    }

    @Override
    public List<Attribute> getAttrByAttrgroupId(Long attrGroupId) {
        List<Attribute> list = null;
        /*查询关联表，获取分组的关联属性*/
        List<AttrAttrgroup> asso = assoAttrAttrGroup.list(new QueryWrapper<AttrAttrgroup>().eq("attr_group_id", attrGroupId));
        /*抽取属性id*/
        if (asso.size() != 0) {
            List<Long> collect = asso.stream().map(AttrAttrgroup::getAttrId).collect(Collectors.toList());
            list = listByIds(collect);
        }
        return list;
    }

    @Override
    public List<Attribute> getAttrByCategoryIdAdnNoAsso(Long categoryId) {
        /*注意此处的属性一定是基本属性（规格参数）而不是销售属性，销售属性没有分组*/
        return baseMapper.getAttrByCategoryIdAdnNoAsso(categoryId);
    }

    @Override
    public List<AttrVo> getAttrByCategoryId(Long categoryId, Integer attrType) {
        List<AttrVo> list = null;
        /*1、查询分类表，获取分类id*/
        Category category = categoryService.getById(categoryId);
        /*2、查询基本数据（属性表）*/
        List<Attribute> attributes = null;
        QueryWrapper<Attribute> wrapper = new QueryWrapper<>();
        if (attrType != 3) {
            /*如果类型参数为3表示查询这个分类下所有属性*/
            if (attrType==-1){
//                查询这个分类下的所有销售属性(包括即使销售属性有事规格参数的值）
                wrapper.in("attr_type",0,2);
            }
            else {
                wrapper.eq("attr_type", attrType);
            }
        }
        wrapper.eq("category_id", categoryId);
        attributes = list(wrapper);
        /*3、如果是规格参数
                获取分组名称
                3.1查询属性分组关联表，获取分组的id,
                3.2通过分组id查询分组信息
            如果是销售属性，就没有分组
        */
        if (attrType == 1) {
            List<Long> attrIds = attributes.stream().map(Attribute::getId).collect(Collectors.toList());
            List<AttrAttrgroup> groups = assoAttrAttrGroup.list(new QueryWrapper<AttrAttrgroup>().in("attr_id", attrIds));
            list = attributes.stream().map(attrItem -> {
                /*我们能肯定满足条件的只有一个，因为属性和分组是多对一的情况，在关联表中不会出现多个相同的属性*/
                Optional<AttrAttrgroup> first = groups.stream().filter(groupItem -> groupItem.getAttrId() == attrItem.getId()).findFirst();
                AttrVo attrVo = new AttrVo();
                BeanUtils.copyProperties(attrItem, attrVo);
                if (first.isPresent()) {//需要判断是否为空，否则直接使用get()方法获取会出现异常
                    AttrAttrgroup attrgroup = first.get();
                    Attrgroup group = groupService.getById(attrgroup.getAttrGroupId());
                    attrVo.setGroupName(group.getGroupName());
                }
                attrVo.setCategoryName(category.getName());
                return attrVo;
            }).collect(Collectors.toList());
        } else {
            /*处理为子类类型集合*/
            list = attributes.stream().map(item -> {
                AttrVo attrVo = new AttrVo();
                BeanUtils.copyProperties(item, attrVo);
                return attrVo;
            }).collect(Collectors.toList());
        }
        log.info("查看收集的结果", list);
        return list;
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        List<Long> longs = baseMapper.selectSearchAttrIds(attrIds);
        return longs;
    }

    @Override
    public List<Attribute> listSaleAttrByCategoryId(Long categoryId) {
        LambdaQueryWrapper<Attribute> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Attribute::getCategoryId,categoryId)
                .in(Attribute::getAttrType,0,2);
        List<Attribute> attributeList = list(wrapper);
        return attributeList;
    }


}
